package com.hjm.project.sign.pos.controller;

import com.hjm.common.utils.SignPicOrder;
import com.hjm.common.utils.Utils;
import com.hjm.common.utils.fastdfs.FastDFSClient;
import com.hjm.framework.config.BlueConfig;
import com.hjm.framework.config.CustomConfig;
import com.hjm.framework.web.controller.BaseController;
import com.hjm.project.bankExpenditure.bankExpenditure.domain.PosOrder;
import com.hjm.project.bankExpenditure.bankExpenditure.service.IBankExpenditureService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import uk.ac.cam.cl.mgk25.jbigkit.JBIG;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author maker
 * @title SignPosController
 * @projectName maker-platform
 * @description
 * @date 2021/1/17 11:22
 */
@Controller
@RequestMapping("/signpos")
public class SignPosController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(SignPosController.class);

    private String prefix = "bankExpenditure/bankExpenditure";

    @Autowired
    private IBankExpenditureService bankExpenditureService;

    /**
     * 获取签名小票
     * 请求来源 0 机器端  1 app 端  2平台端
     * @return
     */
    @GetMapping("getSign")
    public String getSignPic(String serial, String resouce, ModelMap mmap) {
        //根据流水号查看签购单
        FileOutputStream fis=null;
        String signPath="";
        String filepath="";
        File jbig=null,filebmp=null,filetemp=null;
        //获取请求路径
        String ip = CustomConfig.getImgUrl();
        if(serial==null || "".equals(serial) || resouce==null || "".equals(resouce)){
            mmap.put("error", "参数不能为空");
            return prefix +"/outQianGouDan";
        }else{
            try {
                Map dataMap=bankExpenditureService.selectSignatrue(serial);
                if (dataMap!=null){
                    Object ss=dataMap.get("SIGNATURE");
                    PosOrder order=getPosorder(dataMap);
                    //根据流水号查询小票是否存在
                    Map map=bankExpenditureService.selectSignEx(serial);
                    //存在小票  直接用
                    //存在小票  直接用
                    if(map!=null) {
                        String sign_pic_path = (String) map.get("SIGN_PIC_PATH");
                        mmap.put("signPath", ip + sign_pic_path);
                        return prefix +"/outQianGouDan";
                    }else{
                        //签名存在
                        if(ss!=null){
                            //将ss转换为签名图片
                            filepath =  BlueConfig.getProfile();
                            filepath=filepath+"qianzi"+System.currentTimeMillis();
                            jbig = new File(filepath + ".jbig");
                            fis = new FileOutputStream(jbig);
                            fis.write(Utils.hexStringToBytes(ss.toString()));
                            fis.flush();
                            //将jbig转换成bmp
                            JBIG.jbg2bmp(filepath+".jbig", filepath+".bmp");
                            filebmp=new File(filepath+".bmp");
                            Map<String,String> metaList = new HashMap<String, String>();
                            metaList.put("fileName",filebmp.getName());
                            metaList.put("fileType","qian");
                            //将签名文件上传 获取fid
                            String qianfid = FastDFSClient.uploadFile(filebmp,filebmp.getName(),metaList);
                            if("-1".equals(qianfid)){
                                mmap.put("error","小票生成失败");
                                return prefix +"/outQianGouDan";
                            }
                            //获取背景图片
                            ClassPathResource resource = new ClassPathResource("static/img/bg.png");
                            signPath =BlueConfig.getProfile() + "sign_" + System.currentTimeMillis() + ".jpg";
                            //重绘图片
                            SignPicOrder.exportImg(order, resource.getInputStream(), filepath + ".bmp", true, signPath, true, "dqian");
                            filetemp = new File(signPath);
                            metaList.put("fileName", filetemp.getName());
                            metaList.put("fileType", "signPic");
                            //上传签名小票
                            String signfid = FastDFSClient.uploadFile(filetemp, filetemp.getName(), metaList);
                            if ("-1".equals(signfid)) {
                                mmap.put("error", "小票生成失败");
                                return prefix +"/outQianGouDan";
                            }
                            Map<String, Object> data = new HashMap<>();
                            //添加数据
                            data.put("serial", serial);
                            data.put("qianm_pic_path", qianfid);
                            data.put("sign_pic_path", signfid);
                            data.put("resouce", 2);
                            //新增记录
                            bankExpenditureService.insertsignpic(data);

                            mmap.put("signPath", ip + signfid);
                            return prefix +"/outQianGouDan";
                        }else{
                            //获取背景图片
                            ClassPathResource resource = new ClassPathResource("static/img/bg.png");
                            signPath = BlueConfig.getProfile() + "sign_" + System.currentTimeMillis() + ".jpg";
                            //重绘图片
                            SignPicOrder.exportImg(order,resource.getInputStream(),"",true,signPath,false,"dqian");
                            filetemp=new File(signPath);
                            Map<String,String> metaList = new HashMap<String, String>();

                            //上传签名小票
                            String signfid = FastDFSClient.uploadFile(filetemp,filetemp.getName(),metaList);
                            if("-1".equals(signfid)){
                                mmap.put("error","小票生成失败");
                                return prefix +"/outQianGouDan";
                            }
                            Map<String,Object> data=new HashMap<>();
                            //添加数据
                            data.put("serial",serial);
                            data.put("qianm_pic_path","mianqian");
                            data.put("sign_pic_path",signfid);
                            data.put("resouce",resouce);

                            //新增记录
                            bankExpenditureService.insertsignpic(data);
                            mmap.put("signPath", ip + signfid);
                            return prefix +"/outQianGouDan";
                        }
                    }
                }else{
                    mmap.put("error", "数据错误");
                    return prefix +"/outQianGouDan";
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("查看外部签购单异常:",e);
                mmap.put("error", "数据异常");
                return prefix +"/outQianGouDan";
            }finally {

                try {
                    if(fis!=null){
                        fis.close();
                    }
                    //删除jbig
                    if(jbig!=null && jbig.exists()){
                        jbig.delete();
                    }
                    //删除bmp
                    if(filebmp!=null && filebmp.exists()){
                        filebmp.delete();
                    }
                    //删除电子签名
                    if(filetemp!=null && filetemp.exists()){
                        filetemp.delete();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("查看外部签购单资源关闭异常:",e);
                }
            }
        }
    }
    /**
     *  订单实体
     * @param dataMap
     * @return
     */
    public PosOrder getPosorder(Map dataMap){
        PosOrder order = new PosOrder();
        if (dataMap.get("INFO")!=null){
            String[] info=dataMap.get("INFO").toString().split(",");
            //商户名称
            order.setMerchantName(info[1]== null ? "" : info[1] + "");
            //商户编号
            order.setMerchantNo(info[0] == null ? "" : info[0] + "");
        }else {
            //商户名称
            order.setMerchantName("");
            //商户编号
            order.setMerchantNo("");
        }
        //卡类型
        order.setCardtype(dataMap.get("CARDTYPE") == null ? "" : dataMap.get("CARDTYPE") + "");
        //授权码
        order.setAir(dataMap.get("AIR")==null?"":dataMap.get("AIR")+"");
        //终端编号
        order.setBankpos(dataMap.get("CATI")==null?"":dataMap.get("CATI")+"");
        //内部参考号
        order.setTerno(dataMap.get("TERNO")==null?"":dataMap.get("TERNO")+"");
        //发卡行名称
        order.setBankname(dataMap.get("CARDNAME")==null?"":dataMap.get("CARDNAME")+"");
        //卡号
        order.setPan(dataMap.get("PAN")==null?"":dataMap.get("PAN")+"");
        //凭证号
        order.setStan(dataMap.get("STAN")==null?"":dataMap.get("STAN")+"");
        //参考号
        order.setRrno(dataMap.get("RRNO")==null?"":dataMap.get("RRNO")+"");
        //交易日期
        order.setRiqi(dataMap.get("LOCALDATE")+"  "+dataMap.get("LOCALTIME"));
        //交易金额
        order.setAmount(dataMap.get("AMOUNT")==null?"0.00":dataMap.get("AMOUNT")+"");

        return order;
    }

}
